package com.lc.projects.unit.thread.part04.test1;

import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

//执行器中控制任务的完成
public class Test7 {
	public static void main(String[] args) {
		ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
		ResultTask[] resultTasks = new ResultTask[5];

		for (int i = 0; i < resultTasks.length; i++) {
			Task7 task = new Task7("Task" + i);
			resultTasks[i] = new ResultTask(task);
			executor.submit(resultTasks[i]);
		}

		try {
			TimeUnit.SECONDS.sleep(2);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		for (int i = 0; i < resultTasks.length; i++) {
			resultTasks[i].cancel(false);
		}

		for (int i = 0; i < resultTasks.length; i++) {
			try {
				if (!resultTasks[i].isCancelled()) {
					System.out.println(resultTasks[i].get());
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
		}

		executor.shutdown();

	}
}

class Task7 implements Callable<String> {
	private String name;

	public Task7(String name) {
		super();
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String call() throws Exception {
		try {
			long duration = (long) (Math.random() * 10);
			System.out.println(this.name + " wait " + duration);
			TimeUnit.SECONDS.sleep(duration);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "Hello, I'm " + name;
	}

}

class ResultTask extends FutureTask<String> {
	private String name;

	public ResultTask(Callable<String> callable) {
		super(callable);
		this.name = ((Task7) callable).getName();
	}

	@Override
	protected void done() {
		super.done();
		if (isCancelled()) {
			System.out.println(this.name + " has been cancelled.");
		} else {
			System.out.println(this.name + " has done.");
		}

	}

}
